<!DOCTYPE html>
<html>
<head>
<script src="../../resources/js-test.js"></script>
</head>
<body>
<script>
jsTestIsAsync = true;
var worker = new Worker('../../fast/canvas/resources/canvas-createImageBitmap-blob-in-workers.js');

description('Test race condition for createImageBitmap from blob in workers and main.');

var imgWidth = 300;
var imgHeight = 150;
var numOfBitmaps = 5;
var bitmapArray = [];

var canvas1 = document.createElement("canvas");
var ctx1 = canvas1.getContext("2d");
ctx1.fillStyle = "#FF0000";
ctx1.fillRect(0, 0, imgWidth, imgHeight);

function compareImageData(data1, data2)
{
    if (data1.length != data2.length) {
        testFailed("The two image have different dimensions");
        finishJSTest();
    }
    for (var i = 0; i < data1.length; i++) {
        if (data1[i] != data2[i]) {
            testFailed("The two image have different pixel data");
            finishJSTest();
        }
    }
}

var getMessageFromWorker = new Promise((resolve, reject) => {
    function onMessage(e) {
        resolve(e.data.data);
        worker.removeEventListener("message", onMessage);
    }
    worker.addEventListener("message", onMessage);
});

// check that the created ImageBitmaps from worker and main have the same pixel
// data as the source, which is the canvas1.toBlob
var newImg = new Image();
canvas1.toBlob(function(blob) {
    worker.postMessage(blob);
    for (var i = 0; i < numOfBitmaps; i++) {
        createImageBitmap(blob).then(imageBitmap => {
            bitmapArray.push(imageBitmap);
            if (bitmapArray.length == numOfBitmaps) {
                var url = URL.createObjectURL(blob);
                newImg.src = url;
            }
        });
    }
});

var imageLoaded = new Promise((resolve, reject) => {
    newImg.onload = function() {
        var canvas2 = document.createElement("canvas");
        var ctx2 = canvas2.getContext("2d");
        ctx2.drawImage(newImg, 0, 0, imgWidth, imgHeight);
        resolve(ctx2.getImageData(0, 0, imgWidth, imgHeight).data);
    };
});

Promise.all([imageLoaded, getMessageFromWorker]).then(([imageDataFromImg, imageBitmapFromWorker]) => {
    var canvas3 = document.createElement("canvas");
    var ctx3 = canvas3.getContext("2d");
    for (var i = 0; i < numOfBitmaps; i++) {
        ctx3.clearRect(0, 0, imgWidth, imgHeight);
        ctx3.drawImage(bitmapArray[i], 0, 0, imgWidth, imgHeight);
        var imageData = ctx3.getImageData(0, 0, imgWidth, imgHeight).data;
        compareImageData(imageData, imageDataFromImg);
    }

    ctx3.clearRect(0, 0, imgWidth, imgHeight);
    ctx3.drawImage(imageBitmapFromWorker, 0, 0, imgWidth, imgHeight);
    var imageData = ctx3.getImageData(0, 0, imgWidth, imgHeight).data;
    compareImageData(imageData, imageDataFromImg);
    testPassed("ImageBitmaps created from blob in worker and in main have the same pixel data");
    finishJSTest();
});

</script>
</body>
</html>
